package com.gitee.sop.sopauth.controller;

import com.gitee.sop.servercommon.annotation.Open;
import com.gitee.sop.servercommon.result.R;
import com.gitee.sop.servercommon.util.StringUtils;
import com.gitee.sop.servercommon.util.UploadUtil;
import com.gitee.sop.sopauth.service.ISysFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.Extension;
import io.swagger.annotations.ExtensionProperty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 文件请求处理
 *
 * @author wlx
 */
@Api(tags = "文件接口")
@RestController
@RequestMapping("/filesystem")
public class SysFileController {
    private static final Logger log = LoggerFactory.getLogger(SysFileController.class);

    @Autowired
    private ISysFileService sysFileService;

    /**
     * 文件上传请求
     */
    @ApiOperation(value = "文件上传", notes = "可上传多个文件"
            // 多文件上传、不确定文件数量上传，必须申明下面这句，否则沙盒界面不会出现上传控件
            , extensions = @Extension(properties = @ExtensionProperty(name = "multiple", value = "multiple")))
    @Open("open.file.upload")
    @PostMapping(value = "upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<?> upload(HttpServletRequest request) {
        try {
            Collection<MultipartFile> uploadFiles = UploadUtil.getUploadFiles(request);
            List<String> uploadUrl = new ArrayList<>();
            // 获取上传的文件
            for (MultipartFile multipartFile : uploadFiles) {
                String url = sysFileService.uploadFile(multipartFile);
                if (StringUtils.isNotBlank(url)) {
                    uploadUrl.add(url);
                }
            }
            // 上传并返回访问地址
            return R.ok(uploadUrl);
        } catch (Exception e) {
            log.error("上传文件失败", e);
            return R.fail(e.getMessage());
        }
    }
}